<template>
  <q-card flat class="full-height column">
    <q-item v-if="userid">
      <q-item-section top avatar>
        <q-avatar>
          <img :src="getAvatar(userid, 'big')" />
        </q-avatar>
      </q-item-section>
      <q-item-section>
        <q-item-label class="relative-position">
          {{ nickname }}
          <q-inner-loading :showing="data.loading.nickname">
            <q-spinner size="xs" color="primary" />
          </q-inner-loading>
          <q-popup-edit v-model="data.nickname" v-slot="scope">
            <q-input
              v-model="scope.value"
              dense
              autofocus
              counter
              @keyup.enter="scope.set"
            >
              <template v-slot:append>
                <q-btn
                  flat
                  dense
                  color="blue"
                  label="保存"
                  @click.stop.prevent="scope.set"
                  :disable="
                    scope.validate(scope.value) === false ||
                    scope.initialValue === scope.value
                  "
                />
              </template>
            </q-input>
          </q-popup-edit>
        </q-item-label>
        <q-item-label caption lines="2">
          {{ userid }}
        </q-item-label>
      </q-item-section>
      <q-item-section side v-if="cookie">
        <q-btn color="primary" label="退出" flat dense @click="logout" />
      </q-item-section>
      <q-item-section side v-else>
        <q-btn color="primary" label="重新登录" flat dense @click="login" />
      </q-item-section>
    </q-item>

    <q-item class="col" tag="label" v-ripple v-else>
      <q-item-section>
        <q-item-label class="text-center">
          <q-btn color="primary" dense flat label="登录账号" @click="login" />
        </q-item-label>
      </q-item-section>
    </q-item>
    <template v-if="!!userid">
      <q-separator inset />
      <q-item v-ripple="!!userid" :tag="!!userid ? 'label' : ''">
        <q-item-section>
          <q-item-label :class="{ 'text-grey': !data.enable }">
            {{ data.enable ? "已启用" : "已禁用" }}
          </q-item-label>
        </q-item-section>
        <q-item-section side>
          <q-toggle
            v-model="data.enable"
            dense
            :disable="!userid || data.loading.enable"
          />
        </q-item-section>
      </q-item>
      <q-separator inset />
      <q-item clickable @click="openWork">
        <q-item-section>
          <q-item-label>进入工作台</q-item-label>
        </q-item-section>
        <q-item-section side>
          <q-icon name="chevron_right" />
        </q-item-section>
      </q-item>
      <q-separator inset />
      <q-item clickable @click="openIm">
        <q-item-section>
          <q-item-label>在线客服</q-item-label>
        </q-item-section>
        <q-item-section side>
          <q-icon name="chevron_right" />
        </q-item-section>
      </q-item>
    </template>
    <q-separator inset />
    <q-item>
      <q-item-section>
        <q-item-label>过期时间</q-item-label>
      </q-item-section>
      <q-item-section side>
        <q-item-label caption>
          <q-btn
            color="primary"
            v-if="data.isExpire"
            label="续费"
            dense
            flat
            @click="toPayment"
          />

          <span v-else>{{ data.expire }}</span>
        </q-item-label>
      </q-item-section>
    </q-item>
  </q-card>
</template>

<script>
import { useQuasar } from "quasar";
import { IM, zbjLoginWindow } from "src/assets/electron";
import { diffTime, getAvatar, isExpire, parseCookie } from "src/assets/utils";
import { api } from "src/boot/axios";
import { computed, defineComponent, reactive } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import BuyAccountDialogVue from "../dialogs/BuyAccountDialog.vue";

export default defineComponent({
  name: "ComponentsItemsAccountItemVue",
  props: {
    accounts_id: Number,
    userid: [Number, String],
    nickname: String,
    enable: [String, Number, Boolean],
    expires_time: Number,
    cookie: String,
  },
  setup(props) {
    const $router = useRouter();
    const $q = useQuasar();
    const $store = useStore();
    const data = reactive({
      loading: {
        nickname: false,
        enable: false,
      },
      isExpire: computed(() => isExpire(props.expires_time)),
      nickname: computed({
        get: () => props.nickname,
        set: (val) => {
          data.loading.nickname = true;
          $store
            .dispatch("persisted/modifyAccount", {
              accounts_id: props.accounts_id,
              nickname: val,
            })
            .then(() => (data.loading.nickname = false));
        },
      }),
      enable: computed({
        get: () => !!props.enable,
        set: (val) => {
          data.loading.enable = true;
          $store
            .dispatch("persisted/modifyAccount", {
              accounts_id: props.accounts_id,
              enable: val,
            })
            .then(() => (data.loading.enable = false));
        },
      }),
      expire: computed(() => {
        if (props.expires_time === 0) {
          return "永久";
        }

        if (isExpire(props.expires_time)) {
          return "续费";
        }
        const currentTime = parseInt(+new Date() / 1000);
        const diff = diffTime(props.expires_time - currentTime);
        if (diff.days) {
          return diff.days + "天";
        }
        if (diff.hours) {
          return diff.hours + "小时";
        }
        if (diff.minutes) {
          return diff.minutes + "分钟";
        }
        if (diff.seconds) {
          return diff.seconds + "秒";
        }
        return "";
      }),
    });

    function toPayment() {
      $router.push("/payment/" + props.accounts_id);
    }

    return {
      data,
      getAvatar,
      openWork() {
        if (props.userid) {
          $router.push({
            path: "/browser",
            query: {
              id: props.userid,
            },
          });
        }
      },
      openIm() {
        if (props.userid) {
          $router.push({
            path: "/server",
            query: {
              id: props.userid,
            },
          });
        }
      },
      login() {
        if (data.isExpire) {
          $q.dialog({
            title: "续费",
            message: "账号过期，请您续费后使用。",
            ok: "去充值",
          }).onOk(toPayment);
          return;
        }

        zbjLoginWindow.show().then((res) => {
          const cookie = parseCookie(res.cookie);
          if (!cookie || !cookie.data.userid) {
            $q.notify("登录失败");
            return;
          }

          for (const id in $store.state.persisted.accounts) {
            const acc = $store.state.persisted.accounts[id];
            if (acc.userid == cookie.data.userid) {
              api.post("accounts/logout", { accounts_id: id });
            }
          }
          api
            .post("accounts/login", {
              accounts_id: props.accounts_id,
              cookie: cookie.string,
              brandname: cookie.data.brandname,
              nickname: cookie.data.nickname,
              userid: cookie.data.userid,
            })
            .then(() => {
              IM.login(cookie.data);
              $store.dispatch("persisted/syncAccounts");
            });
        });
      },
      logout() {
        $q.dialog({
          title: "退出",
          message: `确定退出${props.nickname}吗？`,
          cancel: {
            label: "取消",
            flat: true,
            color: "grey",
          },
          ok: "确定",
        }).onOk(() => {
          $q.loading.show();
          api
            .post("accounts/logout", { accounts_id: props.accounts_id })
            .then(() => {
              $store.dispatch("persisted/syncAccounts");
            })
            .finally(() => $q.loading.hide());
        });
      },
      toPayment,
    };
  },
});
</script>
